<?php
namespace app\admin\module;

use app\common\model\Spec;
use app\common\model\SpecValue;
use think\Exception;

class SpecModule {
    public static function page($pageSize = 10){
        return Spec::where([])->order("id",'desc')->paginate($pageSize);
    }

    public static function create($data){
        $exists = Spec::where(['spec_name'=>$data['spec_name']])->find();
        if($exists){
            throw new Exception("已经存在该规格了，不能重复添加");
        }
        return Spec::create($data);
    }

    public static function update($data){
        $exists = Spec::where(['spec_name'=>$data['spec_name'],'id'=>['<>',$data['id']]])->find();
        if($exists){
            throw new Exception("已经存在该规格了，不能重复添加");
        }
        return Spec::update($data,['id'=>$data['id']]);
    }

    public static function remove($id){
        //不影响订单 但是影响商品 要不要判断呢 还是判断一下
        //到处理sku的时候再回头来处理
        return Spec::destroy($id);
    }

    public static function allVal($specId){
         return SpecValue::where(['spec_id'=>$specId])->select();
    }


    public static function createVal($data){
        $exists = SpecValue::where($data)->find();
        if($exists){
            throw new Exception('该规格值已经存在了，无需重复添加');
        }
        return SpecValue::create($data);
    }


    public static function updateVal($data){
        $exists = SpecValue::where(['spec_id'=>$data['spec_id'],'spec_value'=>$data['spec_value']])->find(); //自己存在也算
        if($exists){
            throw new Exception('该规格值已经存在了，无需重复添加');
        }
        return SpecValue::update($data,['id'=>$data['id']]);
    }

    public static function removeVal($id){
        //判断一下
        return SpecValue::destroy($id);
    }
}
